import store from '@/store'
import { sum } from '@/core/util.js'
import * as RongIMLib from '@rongcloud/imlib-v4'
import ObserverList from './observer'
import { $msg } from '@/core/msg'

export default function(im) {
	let conversationList = []

	function watchConversation(fn) {
		im.watch({
			conversation({ updatedConversationList }) {
				conversationList = im.Conversation.merge({
					conversationList,
					updatedConversationList
				});
				refreshMsgCount()
				fn(conversationList);
			},
		})
	}

	function watchMessage(fn) {
		im.watch({
			message(msg) {
				$msg('有新消息', () => {
					if (fn) fn(msg)
				})
			}
		})
	}

	/**
	 * 获取会话实例
	 * @param {int} 对方ID
	 */
	function getCoversation(targetId) {
		return im.Conversation.get({
			targetId,
			type: RongIMLib.CONVERSATION_TYPE.PRIVATE
		})
	}

	async function refreshMsgCount() {
		let totalMsg = sum(conversationList, r => r.unreadMessageCount)
		store.commit('SET_MSG_DOT_VISIBLE', totalMsg)
	}

	async function clearMsgCount() {
		store.commit('SET_MSG_DOT_VISIBLE', 0)
	}

	/**
	 * 获取会话列表
	 */
	async function getChatList() {
		try {
			let list = await im.Conversation.getList()

			conversationList = im.Conversation.merge({
				conversationList,
				updatedConversationList: list
			});

			refreshMsgCount()

			return conversationList
		} catch (e) {
			console.log('获取会话列表失败');
		}
	}

	function readCoversation(targetId) {
		getCoversation(targetId).read()
	}

	/**
	 * 获取历史消息
	 */
	async function getOldMessage(targetId, count = 20) {
		try {
			let res = await getCoversation(targetId).getMessages({ count })
			return res
		} catch (error) {
			console.log('获取历史消息失败', error);
		}
	}

	/**
	 * 发送文字、表情消息
	 */
	async function sendMsg(targetId, content) {
		return await getCoversation(targetId).send({
			messageType: RongIMLib.MESSAGE_TYPE.TEXT,
			content: { content }
		})
	}

	/**
	 * 发送图文消息
	 * @param {Object} targetId
	 * @param {Object} title
	 * @param {Object} content
	 * @param {Object} imageUri
	 * @param {Object} url
	 */
	async function sendRichMsg(targetId, title, content, imageUri, url) {
		return await getCoversation(targetId).send({
			messageType: RongIMLib.MESSAGE_TYPE.RICH_CONTENT,
			content: { title, content, imageUri, url }
		})
	}

	return {
		getCoversation,
		getChatList,
		getOldMessage,
		sendMsg,
		sendRichMsg,
		readCoversation,
		watchConversation,
		watchMessage,
		clearMsgCount
	}
}
